'use client'
import React, { useState, useEffect } from 'react';
import './index.scss'
import { Input, Upload, Select, Space, Button, message, Modal } from 'antd';
import Active from '@/app/store/active'
import { UploadOutlined } from '@ant-design/icons';
import KeyStore from '@/app/store/key'
import Markdown from '@/app/components/MarkDown/page'
const { TextArea } = Input;


interface ModaluiProps {
    setDate: (value: boolean) => void;
    open: boolean
}

const Modalui: React.FC<ModaluiProps> = (({ setDate, open }) => {
    const { getDevice } = Active()
    const [userValue, setUserValue] = useState('');
    const [agentValue, setAgentValue] = useState('');
    const [Row, setRow] = useState(27)
    const [selectValue, setSelectValue] = useState('app-n2Erwxvy9EhlDb8ho1RsnY4Y')
    const [fileList, setFileList] = useState<any>([])
    const user = KeyStore((state) => state.user)
    const key = KeyStore((state) => state.key)
    const [is, setis] = useState(false)

    const options = [
        {
            value: 'app-n2Erwxvy9EhlDb8ho1RsnY4Y',
            label: '文本纠错',
        },
        {
            value: 'app-DTj4TTzqKWAavD9OquEkwZuU',
            label: '文本润色',
        },
    ];
    // const options = [
    //     {
    //         value: 'app-AAJkqpKSQWjjV5XxtqAvBFUi',
    //         label: '文本纠错',
    //     },
    //     {
    //         value: 'app-oJJTWnidOhQIwt04MoZzLrYx',
    //         label: '文本润色',
    //     },
    // ];
    const props: any = {
        name: 'file',
        action: `/api/files/upload`,
        headers: {
            authorization: `Bearer app-5ccHqEWlqZ0AbPIxyYDSjYMd`,
        },
        fileList,
        method: 'POST',
        data: () => ({
            user: user,
        }),
        beforeUpload(file: any) {
            const isImage = file.type.startsWith('image/');
            if (isImage) {
                message.error('不允许上传图片!');
                return false;
            }
            return true;
        },
        onSuccess(response: any, file: any) {
            response['status'] = 'done'
            setFileList([response, ...fileList])

            try {
                message.success(`${file.name} 上传成功`);
            } catch {
                message.error("上传失败");
            }
        },
        onRemove(file: any) {
            setFileList((prev: any) => prev.filter((f: any) => f.id !== file.id));
            return true
        },
    };


    useEffect(() => {
        if (getDevice() === 'phone') {
            setRow(10)
        } else {
            setRow(27)
        }
    }, [])

    const handleChange = (value: string) => {
        setSelectValue(value)
    };

    const handleClick = () => {
        let data = {}
        if (fileList.length === 0) {
            data = {
                txt: userValue
            }
        } else {
            data = {
                word: {
                    type: 'document',
                    transfer_method: 'local_file',
                    upload_file_id: fileList[0].id
                }
            }
        }
        if (userValue != '' && fileList.length != 0) {
            message.error('目前只支持单一文本或者文件')
        } else {
            Getresponse(data)
        }
    }

    async function Getresponse(data: any) {
        setis(true)
        const resp = await fetch(`${process.env.NEXT_PUBLIC_API_URL_READWORD}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + selectValue
            },
            body: JSON.stringify({
                inputs: data,
                response_mode: "streaming",
                user: user,
            })
        });
        let completeAnswer = '';
        let currentData = '';

        if (resp.body) {
            const reader = resp.body.pipeThrough(new TextDecoderStream()).getReader();
            while (true) {
                const { done, value: readValue } = await reader.read();
                if (done) break;
                currentData += readValue;
                while (currentData.includes('data: ')) {
                    const startIndex = currentData.indexOf('data: ') + 6;
                    const endIndex = currentData.indexOf('\n\n', startIndex);
                    let jsonStr;
                    if (endIndex === -1) {
                        jsonStr = currentData.substring(startIndex);
                        currentData = '';
                    } else {
                        jsonStr = currentData.substring(startIndex, endIndex + 2);
                        currentData = currentData.substring(endIndex + 2);
                    }
                    try {
                        const data = JSON.parse(jsonStr);
                        if (data.event === 'text_chunk' && data.data.text) {
                            completeAnswer += data.data.text;
                        }
                    } catch (err) {
                        if (endIndex === -1) {
                            currentData = jsonStr;
                        }
                    }
                }
                setAgentValue(completeAnswer)
            }
        }
        setis(false)
    }

    return <Modal title="纠错/润色" open={open} onOk={() => { setDate(false) }} onCancel={() => setDate(false)} width={'80%'} centered footer={null} >
        <div className='readword'>
            <div className='topword'>
                <div>
                    <TextArea
                        value={userValue}
                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setUserValue(e.target.value)}
                        placeholder="Controlled autosize"
                        autoSize={{ minRows: Row, maxRows: Row }}
                    />
                </div>
                <div>
                    <Markdown content={agentValue} />
                </div>
            </div>
            <div className='button'>
                <Space.Compact>
                    <Upload {...props}>
                        {fileList.length < 1 && <Button icon={<UploadOutlined />}>上传文件</Button>}
                    </Upload>
                    <Select defaultValue="文本纠错" onChange={handleChange} options={options} value={selectValue} />
                    <Button onClick={() => handleClick()} disabled={is}>确定</Button>
                </Space.Compact>
            </div>
        </div>
    </Modal>

})

export default Modalui